package com.dsl.tms.service;

import com.dsl.tms.annotation.LoginRequired;
import com.dsl.tms.entity.db.Admin;
import com.dsl.tms.entity.redis.AdminRedis;
import com.dsl.tms.entity.request.AdminInfo;
import com.dsl.tms.entity.response.AdminTokenMap;
import com.dsl.tms.entity.response.AdminUserMap;
import com.dsl.tms.enums.AdminLoginResult;
import com.dsl.tms.model.LoginModel;
import com.dsl.tms.repository.AdminRepository;
import com.dsl.tms.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.IOException;


@Service
public class AdminService {

    @Autowired
    AdminRepository adminDao;

    @Autowired
    private RedisTemplate redisTemplate;

    private static Logger LOGGER = LoggerFactory.getLogger(AdminService.class);


    public AdminTokenMap login(AdminInfo adminInfo){
        AdminTokenMap adminTokenMap = new AdminTokenMap();
        adminInfo.setPassword(DigestUtils.md5DigestAsHex(adminInfo.getPassword().getBytes()));
        Admin admin = adminDao.findOneByUserNameAndPassword(adminInfo.getUserName(),adminInfo.getPassword());
        if (admin == null){
            adminTokenMap.setResult(LoginModel.getResult(AdminLoginResult.MISS_USER_OR_PASSWORD));
            return adminTokenMap;
        }
        String token = LoginModel.createToken(redisTemplate,admin);
        adminTokenMap.setToken(token);
        adminTokenMap.setResult(LoginModel.getResult(AdminLoginResult.SUCCESS));
        return adminTokenMap;
    }

    @LoginRequired
    public AdminUserMap getUserInfo(String token) {
        AdminUserMap adminUserMap = new AdminUserMap();
        AdminRedis adminRedis = (AdminRedis) redisTemplate.opsForValue().get(token);
        adminUserMap.setUser_id(adminRedis.getUserId());
        adminUserMap.setName(adminRedis.getUserName());
        adminUserMap.setAvator(adminRedis.getAvator());
        try {
            adminUserMap.setAccess(JsonUtil.toList(adminRedis.getAccess()));
        } catch (IOException e) {
            e.printStackTrace();
            adminUserMap.setResult(LoginModel.getResult(AdminLoginResult.PROGRAM_ERR));
        }
        adminUserMap.setResult(LoginModel.getResult(AdminLoginResult.SUCCESS));
        return adminUserMap;
    }

    @LoginRequired
    public AdminTokenMap logout(String token){
        AdminTokenMap adminTokenMap = new AdminTokenMap();
        redisTemplate.delete(token);
        adminTokenMap.setToken(null);
        adminTokenMap.setResult(LoginModel.getResult(AdminLoginResult.SUCCESS));
        return adminTokenMap;
    }



}
